<template>
  <div class="app-container">
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>项目负责人</h3>
      <!-- <el-button size="small" type="success" @click="handleAdd">
        <i class="el-icon-plus" />
        新增
      </el-button> -->
    </div>
    <!-- 自定义下划线，替代el-divider -->
    <div class="custom-divider" />
    <!-- 操作按钮区域 -->
    <!-- <el-card>
      <div class="table-operations-wrapper">
        <div class="table-operations">
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >
            {{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            ></i>
          </el-button>
          <el-button size="small" type="success" @click="handleAdd">
            <i class="el-icon-plus"></i>
            新增
          </el-button>
          <el-button type="warning" size="small" @click="handleEdit">
            <i class="el-icon-edit"></i>
            修改
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete">
            <i class="el-icon-delete"></i>
            批量删除
          </el-button>
        </div>
      </div>
    </el-card> -->

    <!-- 搜索区域使用 transform 包裹 -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <el-form
          ref="searchForm"
          :model="listQuery"
          :inline="true"
          label-width="90px"
        >
          <el-form-item label="负责人:">
            <el-select
              v-model="listQuery.directorId"
              placeholder="请选择负责人"
              clearable
              style="width: 200px"
              @change="handleDirectorChange"
            >
              <el-option
                v-for="item in directorList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="申请时间:">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              style="width: 350px"
              @change="handleDateChange"
            />
          </el-form-item>

          <el-form-item label="状态:">
            <el-select
              v-model="listQuery.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
              @change="handleStatusChange"
            >
              <el-option label="全部" :value="2" />
              <el-option label="待处理" :value="0" />
              <el-option label="已处理" :value="1" />
              <el-option label="已驳回" :value="-1" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-collapse-transition>

    <!-- 表格区域 -->
    <div class="table-operations-wrapper">
      <div class="table-operations">
        <el-form
          ref="searchForm"
          :model="listQuery"
          :inline="true"
          label-width="90px"
        >
          <el-form-item label="负责人:">
            <el-select
              v-model="listQuery.directorId"
              placeholder="请选择负责人"
              clearable
              filterable
              remote
              @focus="onDirectorFocus"
              :remote-method="remoteSearchDirectors"
              :loading="directorLoading"
              style="width: 200px"
              @change="handleDirectorChange"
            >
              <el-option
                v-for="item in directorList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="申请时间:">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
              style="width: 350px"
              @change="handleDateChange"
            />
          </el-form-item>

          <el-form-item label="状态:">
            <el-select
              v-model="listQuery.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
              @change="handleStatusChange"
            >
              <el-option label="全部" :value="2" />
              <el-option label="待处理" :value="0" />
              <el-option label="已处理" :value="1" />
              <el-option label="已驳回" :value="-1" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >
            {{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            ></i>
          </el-button> -->
        <!-- <el-button size="small" type="success" @click="handleAdd">
            <i class="el-icon-plus"></i>
            新增
          </el-button> -->
      </div>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="materialList"
      border
      style="width: 100%; margin-top: 20px"
    >
      <!-- <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column> -->
      <el-table-column type="index" label="序号" width="100" align="center" />
      <el-table-column label="商品明细" width="330" align="center">
        <template slot-scope="scope">
          <div
            v-if="scope.row.list && scope.row.list.length > 0"
            class="goods-detail-container"
          >
            <!-- 循环渲染每个商品项 -->
            <div
              v-for="(item, index) in scope.row.list"
              :key="index"
              class="goods-item"
            >
              <div class="goods-row">
                <!-- 商品名称和数量 -->
                <div class="goods-name">{{ item.goodsName }}</div>
                <div class="goods-number">
                  数量: <span class="number-value">{{ item.number }}</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-goods">暂无商品</div>
        </template>
      </el-table-column>
      <el-table-column
          prop="directorName"
          label="负责人"
          align="center"
        ></el-table-column>
        <el-table-column align="center" prop="chargePersonName" label="审批人">
        </el-table-column>
      <!-- <el-table-column align="center" prop="goodsName" label="商品名称" /> -->
      <!-- <el-table-column align="center" prop="chargePersonSuggest" label="意见" />
      <el-table-column align="center" prop="number" label="数量" /> -->
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <!-- <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            > -->
          <el-button
            type="warning"
            size="small"
            :disabled="scope.row.status === 1 || scope.row.status === -1"
            @click="handleReview(scope.row)"
            >审核</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      width="500px"
    >
      <el-form
        ref="dataForm"
        :model="materialForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商品" prop="goodsId">
          <el-select
            v-model="materialForm.goodsId"
            placeholder="请选择商品"
            style="width: 100%"
          >
            <el-option
              v-for="item in goodsList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="数量" prop="number">
          <el-input
            v-model.number="materialForm.number"
            style="width: 100%"
            placeholder="请输入数量"
          />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="materialForm.type">
            <el-radio :label="1">日常领料</el-radio>
            <el-radio :label="2">工程领料</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="materialForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog title="审核" :visible.sync="reviewDialogVisible" width="500px">
      <el-form
        ref="reviewForm"
        :model="reviewForm"
        :rules="reviewRules"
        label-width="80px"
      >
        <el-form-item label="审核结果" prop="result">
          <el-radio-group v-model="reviewForm.result">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="0">未通过</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="审核意见" prop="suggest">
          <el-input
            v-model="reviewForm.suggest"
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见"
          />
        </el-form-item>

        <!-- <el-form-item label="附件" prop="file">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="handleUpload"
            :before-upload="beforeUpload"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传 jpg/png/pdf 文件
            </div>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReview">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selMaterialRequisitionListApi,
  addMaterialRequisitionApi,
  updateMaterialRequisitionByIdApi,
  delMaterialRequisitionByIdApi,
  selDepartmentHeadInspectListApi,
  updateDepartmentHeadInspectByIdApi,
  selProjectHeadInspectListAPi,
  updateProjectHeadInspectByIdApi,
} from "@/api/material";
import { selGoodsListApi } from "@/api/goods";
import {
  selSupplierListApi,
  selWarehouseListApi,
  selStaffListApi,
} from "@/api/system";
export default {
  name: "MaterialRequisition",
  filters: {
    parseTime(time) {
      return parseTime(time);
    },
  },
  data() {
    return {
      isFilterVisible: false,
      listLoading: false,
      // 查询参数
      listQuery: {
        directorId: "", // 负责人id
        startTime: undefined, // 开始时间
        endTime: undefined, // 结束时间
        status: undefined, // 状态：-1-已驳回 0-待处理 1-已处理 2-全部
        page: 1,
        pageSize: 10,
        userId: this.$store.getters.userId,
      },
      dateRange: [], // 日期范围
      tableData: [], // 表格数据
      materialList: [], // 材料领用单列表
      total: 0, // 总条数
      directorList: [], // 负责人列表
      dialogFormVisible: false,
      // 表单数据 - 按照接口文档定义
      materialForm: {
        id: "", // ID，用于区分新增/编辑
        directorId: "", // 负责人ID integer(int32)
        goodsId: "", // 商品ID integer(int32)
        number: "", // 数量 integer(int32)
        operatorId: "", // 操作人ID string
        remark: "", // 备注 string
        status: "", // 状态 integer(int32)
        warehouseId: "", // 仓库ID integer(int32)
      },
      goodsList: [], // 商品列表
      warehouseList: [], // 仓库列表
      supplierList: [], // 供应商列表
      // 商品查询参数
      goodsQuery: {
        goodsTypeId: null,
        page: 1,
        pageSize: 9999,
        name: "",
        no: "",
        supplierId: null,
        warehouseId: null,
      },
      // 供应商列表查询参数
      supplierQuery: {
        page: 1,
        pageSize: 9999,
        name: "",
        supplierTypeId: "", // 供应商类型
      },
      // 仓库列表查询参数
      warehouseQuery: {
        page: 1,
        pageSize: 9999,
        name: "",
      },
      // 员工列表查询参数
      staffQuery: {
        page: 1,
        pageSize: 9999,
        name: "",
        mobile: "",
        parent: "",
      },
      staffList: [], // 职员列表
      // 表单验证规则
      rules: {
        directorId: [
          { required: true, message: "请选择负责人", trigger: "change" },
        ],
        goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
        number: [{ required: true, message: "请输入数量", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        remark: [
          { max: 200, message: "长度不能超过200个字符", trigger: "blur" },
        ],
      },
      // 审核弹窗相关
      reviewDialogVisible: false,
      // 审核表单
      reviewForm: {
        id: "", // 审核记录ID
        result: 1, // 审核结果：0-驳回 1-通过
        suggest: "", // 审核意见
        file: "", // 附件url
        operatorId: this.$store.getters.userId, // 操作人ID
      },
      reviewRules: {
        result: [
          { required: true, message: "请选择审核结果", trigger: "change" },
        ],
        suggest: [
          { message: "请输入审核意见", trigger: "blur" },
          { max: 200, message: "审核意见不能超过200个字符", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    // 通过id判断是新增还是编辑
    dialogTitle() {
      return this.materialForm.id ? "编辑" : "新增";
    },
  },
  created() {
    this.selProjectHeadInspectList(); // 获取项目负责人列表
    this.selSupplierList();
    this.selGoodsList();
    this.selStaffList();
  },
  methods: {
    // 获取列表数据
    async selProjectHeadInspectList() {
      try {
        const res = await selProjectHeadInspectListAPi(this.listQuery);
        this.materialList = res.records || [];
        this.total = res.total || 0;
      } catch (error) {
        console.error("获取列表失败:", error);
        this.$message.error("获取列表失败");
      }
    },

    // 获取供应商列表
    async selSupplierList() {
      const res = await selSupplierListApi(this.supplierQuery);
      this.supplierList = res.records;
    },
    // 获取仓库列表
    async selWarehouseList() {
      const res = await selWarehouseListApi(this.warehouseQuery);
      this.warehouseList = res.records;
    },
    // 获取员工列表
    async selStaffList() {
      const res = await selStaffListApi(this.staffQuery);
      this.directorList = res.records;
    },
    // 获取商品列表
    async selGoodsList() {
      const res = await selGoodsListApi(this.goodsQuery);
      this.goodsList = res.records || [];
    },

    // 获取状态类型
    getStatusType(status) {
      if (status === 0) {
        return "warning"; // 待处理 - 黄色
      } else if (status === 1) {
        return "success"; // 已处理 - 绿色
      } else if (status === -1) {
        return "danger"; // 已驳回 - 红色
      }
      return "success";
    },

    // 获取状态文本
    getStatusText(status) {
      if (status === 0) {
        return "待处理";
      } else if (status === 1) {
        return "已处理";
      } else if (status === -1) {
        return "已驳回";
      }
      return "已出库";
    },

    // 日期改变
    handleDateChange(val) {
      if (val) {
        // 设置开始时间为当天的 00:00:00
        const startDate = new Date(val[0]);
        startDate.setHours(0, 0, 0, 0);
        this.listQuery.startTime = Math.floor(startDate.getTime() / 1000);

        // 设置结束时间为当天的 23:59:59
        const endDate = new Date(val[1]);
        endDate.setHours(23, 59, 59, 999);
        this.listQuery.endTime = Math.floor(endDate.getTime() / 1000);
      } else {
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
    },

    // 查询按钮点击事件
    handleFilter() {
      this.listQuery.page = 1;
      this.selProjectHeadInspectList();
    },

    // 重置查询条件
    resetFilter() {
      this.dateRange = [];
      this.listQuery = {
        directorId: "",
        startTime: undefined,
        endTime: undefined,
        status: undefined,
        page: 1,
        pageSize: 10,
        userId: this.$store.getters.userId,
      };
      this.selProjectHeadInspectList();
    },

    // 每页条数改变
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.selDepartmentHeadInspectList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.selProjectHeadInspectList();
    },
    // 负责人改变
    handleDirectorChange(val) {
      console.log(val);
      this.listQuery.page = 1;
      this.selProjectHeadInspectList();
    },
    // 状态改变
    handleStatusChange(val) {
      console.log(val);
      this.listQuery.page = 1;
      this.selProjectHeadInspectList();
    },
    // 审核
    handleReview(row) {
      this.reviewForm = {
        id: row.id,
        result: 1,
        suggest: "",
        file: "",
        operatorId: this.$store.getters.userId, // 从store中获取当前用户ID
      };
      this.reviewDialogVisible = true;
    },

    // 查看详情
    handleDetail(row) {
      // TODO: 实现查看详情逻辑
      console.log("查看详情:", row);
    },

    // 新增按钮点击
    handleAdd() {
      this.materialForm = {
        goodsId: "",
        number: "",
        type: 1,
        remark: "",
        operatorId: "",
      };
      this.dialogFormVisible = true;
    },

    // 处理单行编辑
    handleEdit(row) {
      this.materialForm = {
        id: row.id,
        goodsId: row.goodsId,
        number: row.number,
        type: row.type,
        remark: row.remark,
        operatorId: row.operatorId,
      };
      this.dialogFormVisible = true;
    },

    // 处理批量编辑
    handleBatchEdit() {
      const selectedRows = this.$refs.table.selection;
      if (selectedRows.length !== 1) {
        this.$message({
          type: "warning",
          message: "请选择一条记录进行修改",
        });
        return;
      }
      this.handleEdit(selectedRows[0]);
    },

    // 处理单行删除
    async handleDelete(id) {
      try {
        await this.$confirm("确认删除该材料领用记录?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });

        const res = await delMaterialRequisitionByIdApi(id);
        if (res.code === 1) {
          this.$message.success("删除成功");
          this.selDepartmentHeadInspectList();
        } else {
          this.$message.error(res.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除失败:", error);
      }
    },

    // 处理批量删除
    async handleBatchDelete() {
      const selectedRows = this.$refs.table.selection;
      if (selectedRows.length === 0) {
        this.$message({
          type: "warning",
          message: "请选择要删除的记录",
        });
        return;
      }

      try {
        await this.$confirm(
          `确认删除选中的 ${selectedRows.length} 条记录?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        const ids = selectedRows.map((row) => row.id);
        const res = await delMaterialRequisitionByIdApi(ids.join(","));

        if (res.code === 1) {
          this.$message.success("批量删除成功");
          this.selDepartmentHeadInspectList();
        } else {
          this.$message.error(res.msg || "批量删除失败");
        }
      } catch (error) {
        console.error("批量删除失败:", error);
      }
    },

    // 更新提交表单方法
    submitForm() {
      this.$refs.dataForm.validate(async (valid) => {
        if (valid) {
          try {
            const params = {
              goodsId: this.materialForm.goodsId,
              number: this.materialForm.number,
              type: this.materialForm.type,
              remark: this.materialForm.remark,
              operatorId: this.materialForm.operatorId,
            };

            let res;
            if (this.materialForm.id) {
              // 编辑
              res = await updateMaterialRequisitionByIdApi({
                ...params,
                id: this.materialForm.id,
              });
            } else {
              // 新增
              res = await addMaterialRequisitionApi(params);
            }

            if (res.code === 1) {
              this.$message.success(
                `${this.materialForm.id ? "编辑" : "新增"}成功`
              );
              this.dialogFormVisible = false;
              this.selDepartmentHeadInspectList();
            } else {
              this.$message.error(res.msg || "操作失败");
            }
          } catch (error) {
            console.error("操作失败:", error);
            this.$message.error("操作失败");
          }
        }
      });
    },

    // 文件上传前的验证
    beforeUpload(file) {
      const isValidType = [
        "image/jpeg",
        "image/png",
        "application/pdf",
      ].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isValidType) {
        this.$message.error("只能上传 JPG/PNG/PDF 格式的文件!");
        return false;
      }
      if (!isLt5M) {
        this.$message.error("文件大小不能超过 5MB!");
        return false;
      }
      return true;
    },

    // 自定义上传方法
    async handleUpload(params) {
      try {
        const formData = new FormData();
        formData.append("file", params.file);
        // 调用上传文件的接口
        const res = await uploadFileApi(formData);
        if (res.code === 1) {
          this.reviewForm.file = res.data;
          this.$message.success("文件上传成功");
        } else {
          this.$message.error(res.msg || "文件上传失败");
        }
      } catch (error) {
        console.error("文件上传失败:", error);
        this.$message.error("文件上传失败");
      }
    },

    // 提交审核
    async submitReview() {
      this.$refs.reviewForm.validate(async (valid) => {
        if (valid) {
          try {
            const res = await updateProjectHeadInspectByIdApi(this.reviewForm);
            if (res.code === 1) {
              this.$message.success("审核提交成功");
              this.reviewDialogVisible = false;
              this.selProjectHeadInspectList(); // 刷新列表
            } else {
              this.$message.error(res.msg || "审核提交失败");
            }
          } catch (error) {
            console.error("审核提交失败:", error);
            this.$message.error("审核提交失败");
          }
        }
      });
    },
    // 负责人选择获取焦点时加载数据
    onDirectorFocus() {
      this.directorLoading = true;
      this.remoteSearchDirectors("");
    },
    // 远程搜索负责人
    async remoteSearchDirectors(query) {
      try {
        const res = await selStaffListApi({
          page: 1,
          pageSize: 9999,
          name: query,
        });
        this.directorList = res.records || [];
      } catch (error) {
        console.error("搜索负责人失败:", error);
        this.$message.error("搜索负责人失败");
        this.directorList = [];
      } finally {
        this.directorLoading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* 商品明细样式 */
.goods-detail-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  text-align: left;
  padding: 5px;
}

.goods-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.goods-name {
  width: 150px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 10px;
}

.goods-number {
  width: 100px;
  color: #606266;
}

.number-value {
  color: #409eff;
  font-weight: 500;
}

.no-goods {
  color: #909399;
  padding: 10px 0;
}

/* 自定义下划线 */
.custom-divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 13px 0;
}

.pagination-container {
  text-align: right;
}
</style>
